<template>
  <view>

    <view class="color-box" :style="'background: url(' +  imgpath + 'luyi/unit/2023/11/01/3011.png);'">
      <view class="user-info">
        <view class="img-box">
          <image src="/static/images/avatar.jpg"></image>
        </view>
        <view class="info-box">
          <view class="">{{personName}}</view>
          <view class="" style="font-size: 28rpx; padding-top: 8rpx;">{{personPhone}}</view>
        </view>
      </view>
    </view>

    <view class="info-pos" style="top: 260rpx; margin-left: 20rpx;">
      <view class="qianyue-top">
        <view class="qianyue-info">
          <view class="images">
            <image src="/static/images/1922.png"></image>
          </view>
          <view class="qianyue-text">签约信息</view>
        </view>

        <view class="qianyue-detail" @click="gotoContract">
          <view class="qianyue-dtext">详细</view>
          <uni-icons type="forward" size="14"></uni-icons>
        </view>
      </view>

      <view class="data-box">
        <view class="data-info">
          <view class="">{{allSigned}}</view>
          <view class="zhushi">全部</view>
        </view>
        <view class="data-info">
          <view class="">{{validContract}}</view>
          <view class="zhushi">有效合同</view>
        </view>
        <view class="data-info">
          <view class="">{{hasEnded}}</view>
          <view class="zhushi">已结束</view>
        </view>
      </view>
    </view>

    <view class="info-pos" style="top: 555rpx; margin-left: 20rpx;">

      <view class="qianyue-top">
        <view class="qianyue-info">
          <view class="images">
            <image src="/static/images/1923.png"></image>
          </view>
          <view class="qianyue-text">薪资信息</view>
        </view>
        <view class="qianyue-detail" @click="gotoSalary">
          <view class="qianyue-dtext">详细</view>
          <uni-icons type="forward" size="14"></uni-icons>
        </view>
      </view>

      <view class="data-box">

        <view class="data-info">
          <view class="">{{total}}</view>
          <view class="zhushi">全部</view>
        </view>
        <view class="data-info">
          <view class="">{{noenter}}</view>
          <view class="zhushi">待确认</view>
        </view>
        <view class="data-info">
          <view class="">{{enter}}</view>
          <view class="zhushi">已确认</view>
        </view>
      </view>

    </view>

    <view class="info-pos" style="top: 850rpx; margin-left: 20rpx;">

      <view class="qianyue-top">
        <view class="qianyue-info">
          <view class="images">
            <image src="/static/images/1924.png"></image>
          </view>
          <view class="qianyue-text">当月考勤</view>
        </view>
        <view class="qianyue-detail" @click="gotojob">
          <view class="qianyue-dtext">详细</view>
          <uni-icons type="forward" size="14"></uni-icons>
        </view>
      </view>

      <view class="data-box">
        <view class="data-info">
          <view class="">{{validWork}}</view>
          <view class="zhushi">有效考勤</view>
        </view>
        <view class="data-info">
          <view class="">{{invalidWork}}</view>
          <view class="zhushi">无效考勤</view>
        </view>
        <view class="data-info">
          <view class="">{{nullWrok}}</view>
          <view class="zhushi">无考勤</view>
        </view>
        <view class="data-info">
          <view class="">{{totalWorkTime === undefined ? 0 : totalWorkTime}}</view>
          <view class="zhushi">累计时长</view>
        </view>
      </view>

    </view>
  </view>
</template>
<script src="/utils/md5.js"></script>"></script>
<script>
  export default {
    data() {
      return {
        imgpath: this.imgpath,
        allSigned: 0, //签约信息-全部
        validContract: 0, //签约信息-有效合同
        hasEnded: 0, //签约信息-已结束
        id: 0,
        personName: 'userName',
        personPhone: '1315123242',
        total: 0,
        noenter: 0,
        enter: 0,
        endTime: "",
        endTimeStr: "",
        isChecked: 3,
        name: "",
        orderBy: "",
        pageNo: 1,
        pageSize: 10,
        personGroup: 0,
        relativeProjectId: 0,
        returnFields: "",
        startTime: "",
        startTimeStr: "",
        totalWorkTime: 0, //累计时长
        validWork: 0, //有效考勤
        invalidWork: 0, //无效考勤
        nullWrok: 0, //无考勤
        pageNum: 1,
        pageSize: 31,
        attendanceList: [],
        days: 31, // 默认31
        // 用于路径传参
        userid: null,
        idCode: null,
        openType: null
      }
    },
    onLoad(options) {
      console.log(options);

      if (options.id != null && options.idCode != null) {
        console.log('通过详细信息');
        this.userid = options.id
        this.personName = options.name
        this.personPhone = options.phone
        this.idCode = options.idCode
        let cardId = options.idCode
        //如果进入这里 那么页面上所有的信息都用 id和身份证来 查询指定的人员的信息 考勤 薪资 和 签约
        this.getattendanceList(this.getFormattedDate(), cardId)
        this.getallsalary(cardId)
        this.getContract(this.idCode)
        return
      }

      if (options.openType != null && options.openType == 0) {
        // 如果进入这里 那么页面上的所有信息都用身份证 来获取 获取个人的
        console.log('通过个人信息进入');
		console.log('userCode',uni.getStorageSync('userCode'));
		this.idCode =uni.getStorageSync('userCode')
        this.personName = uni.getStorageSync('nickName'),
          this.personPhone = uni.getStorageSync('userMobile'),
          this.openType = options.openType
        // 根据个人信息查询资料 通过请求中自带的token 来查询本人的考勤 薪资 签约
        uni.setNavigationBarTitle({
          title: '个人中心'
        }) // 设置页面标题
        this.getContract()
        // 通过个人中心进入 查询个人信息
        this.getallsalary() // 根据当前的身份证来获取所有的考勤信息
        this.getattendanceList(this.getFormattedDate()) //根据传入的时间 然后再通过token 来获取考勤信息
      } else {
        // 从详情进入
        console.log('既没有通过详细信息进入也没有通过个人进入');
      }

    },
    methods: {
      //返回今天的日期 格式为2023-10-20
      getFormattedDate() {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0'); // Month is 0-based
        const day = String(today.getDate()).padStart(2, '0');

        const formattedDate = `${year}-${month}-00`;
        return formattedDate;
      },

      //跳转到合同详情
      gotoContract() {
		  console.log('this.iscode',this.idCode);
        uni.navigateTo({
          url: '../contract/labourSigning?card=' + this.idCode,
        });
      },

      //跳转到薪资详情
      gotoSalary() {
        // 判断是不是从个人中心进入
        if (this.openType != null && this.openType == 0) {
          uni.redirectTo({
            url: '/pages/example/salaryManager/index'
          })
        } else {
          uni.redirectTo({
            url: '/pages/example/salaryManager/index?id=' + this.userid + '&card=' + this.idCode
          })
        }
      },

      //跳转考勤详情
      gotojob() {
        // 判断是不是从个人中心进入
        if (this.openType != null && this.openType == 0) {
          uni.redirectTo({
            url: '/pages/example/jobLogging/jobManage'
          })
        } else {
          uni.redirectTo({
            url: '/pages/example/jobLogging/jobManage?id=' + this.userid + '&card=' + this.idCode
          })
        }

      },

      // 获取合同信息
      getContract(idCard = null) {
        uni.$post(this.path + '/contract/queryAll', {
          personCard: idCard || uni.getStorageSync('userCode')
        }).then(res => {
          if (res.code == 200) {
            this.allSigned = res.data.records.length
            for (let i = 0; i < res.data.records.length; i++) {
              if (res.data.records[i].contractStatus == 0) {
                this.hasEnded += 1
              } else if (res.data.records[i].contractStatus == 2) {
                this.validContract += 1
              }
            }
          }else{
            uni.showToast({
              title: '合同信息获取失败',
              icon: 'none'
            })
          }
        })
      },

      //传递日期字符串 返回当月的天数
      getDaysInMonth(dateString) {
        console.log(dateString);
        const validDateString = dateString.replace(/-00$/, '-01');
        // 将日期字符串转换为Date对象
        const date = new Date(dateString);
        // 获取月份的最后一天
        const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

        // 获取最后一天的日期，即月份的总天数
        const totalDays = lastDay.getDate();
        return totalDays;
      },

      //根据年月来获取考勤数据 比如 '2023-09' 不给就默认查31个
      getattendanceList(nowTime = '', CardId = null) {
        // console.log('获取考勤数据携带的参数' , nowTime ,CardId);
        uni.$post(this.path + '/attendance/query', {
          attendanceDate: nowTime,
          attendanceName: '',
          permissionFlag: '',
          personCard: CardId || uni.getStorageSync('userCode'),
          attendanceStatus: 3, //这个是指定查询的考勤状态 这里的状态写死 每次查不管什么状态的考勤都查出来
          relativeProjectName: '',
        }).then(res => {
          if (res.code == 200) {
            this.attendanceList = res.data.records
            // 这里面是这一个的考勤记录 里面每一个对象都是某天的数据
            console.log('拿到的当月的原始数据', this.attendanceList);
            let days = this.getDaysInMonth(this.attendanceList[0].attendanceDate)
            // console.log('传递日期字符串 返回当月的天数',days);
            this.attendanceList.forEach(item => {
              if (item.attendanceStatus == 2) {
                this.validWork++
              } else if (item.attendanceStatus == 1) {
                this.invalidWork++
              }
            })
            this.nullWrok = days - this.attendanceList.length //无考勤
            // 计算当月的累计时长

            this.attendanceList.forEach(item => {
              if (item.attendanceWorkTime == null) {
                item.attendanceWorkTime = 0
              }

              let numTime = parseFloat(item.attendanceWorkTime).toFixed(2)
              this.totalWorkTime += parseFloat(numTime)
            })
            this.totalWorkTime = (this.totalWorkTime == null ? 0 : this.totalWorkTime)
          } else {
            uni.showToast({
              title: '考勤获取失败,请稍候重试',
              icon: 'error'
            })
          }

        })

      },

      // 将前端返回的工作时长 格式化为number 比如 8小时56分钟52秒
      convertTimeToHours(timeString) {
        // 使用正则表达式匹配可能存在的小时、分钟和秒部分
        const regex = /(\d+)时?(\d*)分?(\d*)秒?/;
        const matches = timeString.match(regex);

        if (matches) {
          const hours = parseInt(matches[1], 10);
          const minutes = parseInt(matches[2], 10) || 0; // 默认为0
          const seconds = parseInt(matches[3], 10) || 0; // 默认为0

          // 将分钟和秒数转换为小时的小数
          const hoursDecimal = hours + minutes / 60 + seconds / 3600;

          // 限制小数点后不超过两位
          const roundedHours = parseFloat(hoursDecimal.toFixed(2));

          return roundedHours;
        } else {
          // 如果字符串格式不正确，返回null或者其他错误处理方式
          return null;
        }
      },

      //获取当月的数据
      getNowMonthData() {
        //页面数据之后 遍历当月的考勤数据然后赋值
        this.totalWorkTime = 0
        this.validWork = 0
        this.invalidWork = 0
        this.nullWrok = 0
        let totalWorkTimeTamp = 0 //累计时长
        let validWorkTamp = 0 //有效考勤
        let invalidWorkTamp = 0 //无效考勤
        let nullWorkTamp = 0 //无考勤
        // console.log('获取当月数据');
        console.log(this.attendanceList);
        this.attendanceList.forEach(item => {
          totalWorkTimeTamp += this.convertTimeToHours(item.attendanceWorkTime) //累计时长
          if (item.attendanceStatus == 2) { //有效考勤
            validWorkTamp += 1
          }
          if (item.attendanceStatus == 1) { //无效考勤
            invalidWorkTamp += 1
          }
        })
        // 当月目前的天数 减去 有效和无效考勤 就是无考勤
        nullWorkTamp = this.days - validWorkTamp - invalidWorkTamp

        this.totalWorkTime = totalWorkTimeTamp
        this.validWork = validWorkTamp
        this.invalidWork = invalidWorkTamp
        this.nullWrok = nullWorkTamp
        this.totalWorkTime = (this.totalWorkTime == null ? 0 : this.totalWorkTime)
      },

      // 根据当前的来获取薪资信息
      getallsalary(idCard = null) {
        console.log('获取薪资信息', idCard);
        uni.$post(this.path + '/salary/query', {
          personCard: idCard || uni.getStorageSync('userCode'),
          isChecked: 10,
          salaryDate: '2023-10-01',
          personGroup: '',
          permissionFlag: '',
          pagesize: '',
          pageNo: ''
        }).then(res => {
          console.log('getallsalary', res);
          if (res.code == 200) {
            this.total = res.data.total
            for (let i = 0; i < res.data.records.length; i++) {
              if (res.data.records[i].isChecked == 1 || res.data.records[i].isChecked == 2) {
                this.enter++;
              } else {
                this.noenter++;
              }
            }
          } else {
            uni.showToast({
              title: '获取薪资信息失败',
              icon: 'none'
            })
          }
        })
      }
    },
    created() {

    }
  }
</script>

<style lang="scss">
  .color-box {
    height: 463rpx;
    // background: url('../../../static/images/3011.png');
    border-radius: 0 0 30rpx 30rpx;

    .user-info {
      display: flex;
      align-items: center;

      .img-box {
        position: absolute;
        top: 60rpx;
        left: 40rpx;
        width: 155rpx;
        height: 155rpx;
        border-radius: 50%;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .info-box {
        position: absolute;
        top: 89rpx;
        left: 223rpx;
        font-size: 32rpx;
        color: #fff;
      }
    }
  }

  .info-pos {
    position: fixed;
    height: 275rpx;
    width: 710rpx;
    border-radius: 16rpx;
    margin: 0 20rpx 20rpx 20rpx;
    background-color: #fff;

    .qianyue-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 105rpx;
      border-bottom: 1px solid #afafaf;

      .qianyue-info {
        display: flex;
        align-items: center;
        padding-left: 20rpx;

        .images {
          width: 40rpx;
          height: 40rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .qianyue-text {
          font-size: 32rpx;
          font-weight: 500;
        }
      }

      .qianyue-detail {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #6E81A0;
        font-size: 28rpx;
        padding-right: 46rpx;

        .qianyue-dtext {
          font-size: 24rpx;
        }
      }
    }

    .data-box {
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 150rpx;

      .data-info {
        height: 150rpx;
        width: 30%;
        font-size: 48rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        color: #055DFE;

        .zhushi {
          margin-top: 6rpx;
          font-size: 28rpx;
          color: #AFAFAF;
        }
      }
    }
  }
</style>
